package mbms.mobilebudget.expense;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import mbms.mobilebudget.R;
import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.EnumValues.CurrencyType;
import mbms.mobilebudget.entity.EnumValues.ExpenseCategoryEnum;
import mbms.mobilebudget.entity.Expense;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

@SuppressLint("SimpleDateFormat")
public class ExpenseAddUpdateActivity extends  OrmLiteBaseActivity<DatabaseHandler> {

	private Expense acquiredExpense;
	private Spinner expenseCategorySpinner;
	//private Spinner currencyTypeSpinner;
	private EditText amount;
	private EditText dateofexpensedatepicker;
	private EditText explanation;
	private boolean isAdd = true;
	private boolean isBankAccountElement;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_expense_add_update);
		
		Intent intent = getIntent();
		
		acquiredExpense = (Expense) intent.getSerializableExtra("expense");
		if(acquiredExpense==null){
			Toast.makeText(getApplicationContext(), 
					"Expense not acquired", Toast.LENGTH_SHORT).show();
			return ;
		}
		
		
		if(acquiredExpense.getBankAccount()==null && acquiredExpense.getCreditCard() ==null ){
			Toast.makeText(getApplicationContext(), 
					"Bank account and credit card not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		else if (acquiredExpense.getBankAccount()!=null && acquiredExpense.getCreditCard() !=null ){
			Toast.makeText(getApplicationContext(), 
					"Two foreign acquired objects cause error", Toast.LENGTH_LONG).show();
			return;
			}
		else if(acquiredExpense.getBankAccount()!=null){
			isBankAccountElement = true;
		}
		else{
			isBankAccountElement = false;
		}
		//currencyTypeSpinner = (Spinner) findViewById(R.id.e_currencytypespinner);
		expenseCategorySpinner = (Spinner) findViewById(R.id.e_expensecategoryinput);
		amount = (EditText) findViewById(R.id.e_amountinput);
		dateofexpensedatepicker = (EditText) findViewById(R.id.e_dateinput);
		explanation = (EditText) findViewById(R.id.e_explanation_input);
		expenseCategorySpinner.setAdapter(new ArrayAdapter<ExpenseCategoryEnum>(this, android.R.layout.simple_spinner_item,
				ExpenseCategoryEnum.values()));
	//	currencyTypeSpinner.setAdapter(new ArrayAdapter<CurrencyType>(this, android.R.layout.simple_spinner_item,		CurrencyType.values()));
		
		Button addUpdateButton = (Button)findViewById(R.id.e_addupdatebutton);
		if(acquiredExpense.getId()==null){
			addUpdateButton.setText("Add");
		}
		else{
			addUpdateButton.setText("Update");
			setData();
			isAdd=false;
		}
		
		
	}

	private boolean mandatoryCheck() {
		if (!amount.getText().toString().equals("")
				&& !dateofexpensedatepicker.getText().toString().equals("")) {
			return true;
		} else {
			Toast.makeText(getApplicationContext(),
					"Mandatory fields must be filled", Toast.LENGTH_LONG)
					.show();
			return false;
		}

	}
	public void addUpdateButtonClicked(View view){
		if(mandatoryCheck()&&amountCheck()){
			addUpdateHandler(isAdd);
		}
	}

	private void addUpdateHandler(boolean isAdd){
		if(isAdd){
			addOperation();
		}
		else{
			updateOperation();
		}
	}
	
	private boolean amountCheck(){
		String amountString = amount.getText().toString();
		try {
			Double d =Double.parseDouble(amountString);
			return true;
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(), "Amount is not valid", Toast.LENGTH_SHORT).show();
			return false;
		}
		
	}

	public void addOperation() {
		
		ExpenseManager expenseManager ;
		if(isBankAccountElement){
			expenseManager = new ExpenseManager(getHelper(), getApplicationContext(), acquiredExpense.getBankAccount(),null);
		}
		else{
			expenseManager = new ExpenseManager(getHelper(), getApplicationContext(),null, acquiredExpense.getCreditCard());
		}
		
		Expense addableExpense =retrieveData();
		
		if(expenseManager.addExpense(addableExpense)!=null){
			Log.i("Add", "succesful");
			Toast.makeText(getApplicationContext(), "Add successful", Toast.LENGTH_SHORT).show();
			super.onBackPressed();
		}
		else{
			Toast.makeText(getApplicationContext(), "Add failed", Toast.LENGTH_SHORT).show();
			Log.e("Add", "failed");
		}
		
		
	}
	private Expense retrieveData() {
		String s_amount = amount.getText().toString();
		Double d_amount;
		try {
			d_amount = Double.parseDouble(s_amount);
		} catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(), "Parse double exception", Toast.LENGTH_SHORT).show();
			return null;
		}
		
		String s_explanation = explanation.getText().toString();
		String s_date =dateofexpensedatepicker.getText().toString();
		Date date;
		try {
			date = new SimpleDateFormat("dd/MM/yyy").parse(s_date);
		} catch (ParseException e) {
			Toast.makeText(getApplicationContext(), "Parse date exception", Toast.LENGTH_SHORT).show();
			return null;
		}
		
		ExpenseCategoryEnum e_expensecategoryspinner = (ExpenseCategoryEnum) expenseCategorySpinner.getSelectedItem();
		CurrencyType e_currencytype;
		if(isBankAccountElement){
			e_currencytype = acquiredExpense.getBankAccount().getCurrencyType();
		}
		else{
			e_currencytype = acquiredExpense.getCreditCard().getCurrencyType();
		}
		if (!isAdd){
			e_currencytype = acquiredExpense.getCurrencyType();
		}
		Expense expense = new Expense(null, e_currencytype, d_amount, e_expensecategoryspinner, date, s_explanation,
				acquiredExpense.getBankAccount(),acquiredExpense.getCreditCard());
		return expense;
	}

	private void setData() {
		explanation.setText(acquiredExpense.getExpenseExplanation());
		amount.setText(acquiredExpense.getAmount().toString());
		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		String datet = formatter.format(acquiredExpense.getDateOfExpense());
		dateofexpensedatepicker.setText(datet);
		expenseCategorySpinner.setSelection(acquiredExpense.getExpenseCategory().ordinal());
				
	}
	public void updateOperation() {
		
		ExpenseManager expenseManager ;
		if(isBankAccountElement){
			expenseManager = new ExpenseManager(getHelper(), getApplicationContext(), acquiredExpense.getBankAccount(),null);
		}
		else{
			expenseManager = new ExpenseManager(getHelper(), getApplicationContext(),null, acquiredExpense.getCreditCard());
		}
		
		Expense updatableExpense = retrieveData();		
		updatableExpense.setId(acquiredExpense.getId());
		if(expenseManager.updateExpense(updatableExpense)!=null){
			Log.i("Update", "succesful");
			Toast.makeText(getApplicationContext(), "Update successful", Toast.LENGTH_SHORT).show();
			super.onBackPressed();
			// liste refresh
		}
		else{
			Toast.makeText(getApplicationContext(), "Update failed", Toast.LENGTH_SHORT).show();
			Log.e("Update", "failed");
		}
		
	}
	


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.expense_add_update, menu);
		return true;
	}

}
